//
//  PasswordSaltVC.m
//  SecureNotes
//
//  Created by 杨岑 on 10/19/15.
//  Copyright © 2015 杨岑. All rights reserved.
//

#import "LoginVC.h"
#import "DetailViewController.h"
@import CloudKit;


@interface LoginVC ()

@end

@implementation LoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    CKContainer* container = [CKContainer defaultContainer];
    NSLog(@"%@", container.containerIdentifier);
    [container accountStatusWithCompletionHandler:^(CKAccountStatus accountStatus, NSError * _Nullable error) {
        
        NSLog(@"accountStatusWithCompletionHandler: %@", [NSThread currentThread]);
        
        switch (accountStatus) {
            case CKAccountStatusAvailable:
                NSLog(@"CKAccountStatusAvailable");
            {
                [container fetchUserRecordIDWithCompletionHandler:^(CKRecordID * _Nullable recordID, NSError * _Nullable error) {
                    NSLog(@"fetchUserRecordIDWithCompletionHandler: %@", [NSThread currentThread]);
                    if (error) {
                        NSLog(@"%@", error);
                    } else {
                        NSLog(@"Container %@ user ID: %@", container, recordID.recordName);
                    }
                }];
                
                CKFetchRecordsOperation* op = [CKFetchRecordsOperation fetchCurrentUserRecordOperation];
                op.perRecordProgressBlock = ^(CKRecordID* recordID, double progress) {
                    NSLog(@"perRecordProgressBlock: %@ %.1f", [NSThread currentThread], progress);
                };
                op.perRecordCompletionBlock = ^(CKRecord* record, CKRecordID* recordID, NSError* error) {
                    NSLog(@"perRecordCompletionBlock: %@", [NSThread currentThread]);
                    
                    if (error) {
                        NSLog(@"%@", error);
                    } else {
                        NSLog(@"CloudKit current user: %@", recordID.recordName);
                    }
                };
                [container.privateCloudDatabase addOperation:op];
            }
                break;
                
            case CKAccountStatusNoAccount:
                NSLog(@"CKAccountStatusNoAccount");
                break;
                
            case CKAccountStatusRestricted:
                NSLog(@"CKAccountStatusRestricted");
                break;
                
            default:
                NSLog(@"Unknown account status: %ld", (long)accountStatus);
                break;
        }
        if (error) {
            NSLog(@"%@", error);
        }
        
        if (accountStatus == CKAccountStatusAvailable)
        {
            //UIStoryboard* mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            //UIViewController* mainVC = [mainStoryboard instantiateInitialViewController];
            //[self presentViewController:mainVC animated:YES completion:nil];
            //self.view.hidden = YES;
        }
        else
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                NSString* noAccount = @"iCloud account not available. This app needs an active iCloud account to work.";
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@"iCloud Account Not Available" message:noAccount preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
                    //exit(1);
                }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            });
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Override point for customization after application launch.
    UISplitViewController *splitViewController = (UISplitViewController *)segue.destinationViewController;
    UINavigationController *navigationController = [splitViewController.viewControllers lastObject];
    navigationController.topViewController.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem;
    splitViewController.delegate = self;
}

#pragma mark - Split view

- (BOOL)splitViewController:(UISplitViewController *)splitViewController collapseSecondaryViewController:(UIViewController *)secondaryViewController ontoPrimaryViewController:(UIViewController *)primaryViewController {
    if ([secondaryViewController isKindOfClass:[UINavigationController class]] && [[(UINavigationController *)secondaryViewController topViewController] isKindOfClass:[DetailViewController class]] && ([(DetailViewController *)[(UINavigationController *)secondaryViewController topViewController] detailItem] == nil)) {
        // Return YES to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
        return YES;
    } else {
        return NO;
    }
}

/*
 - (BOOL)splitViewController:(UISplitViewController *)splitViewController showDetailViewController:(UIViewController *)vc sender:(id)sender {
 if ([vc isKindOfClass:[UINavigationController class]]) {
 UINavigationController* nc = (UINavigationController*)vc;
 [nc setToolbarHidden:NO animated:YES];
 }
 return NO;
 }
 */

- (IBAction)login_click:(id)sender {
    [self performSegueWithIdentifier:@"main" sender:self];
}

@end
